package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;

@Slf4j
@Component
public class AlbumListener {

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    AlbumInfoFeignClient albumInfoFeignClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.ALBUM_UP_QUEUE),
            exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = {RabbitConstant.ALBUM_UP_RK}
    ))
    public void upperAlbum(String message, Message msg, Channel channel) {
        long albumId = Long.parseLong(message);
        log.info("接收到专辑服务投递的消息，更新了id为：【{}】的专辑", albumId);
        try {
            // 查询专辑的最新信息
            Result<AlbumInfoIndex> result = albumInfoFeignClient.getAlbumInfoById(albumId);
            Assert.notNull(result, "id为" + albumId + "的专辑不存在");
            AlbumInfoIndex albumInfoIndex = result.getData();
            // 更新专辑索引库
            esTemplate.save(albumInfoIndex);
            SuggestIndex titleSuggestIndex = new SuggestIndex();
            titleSuggestIndex.setId(null);
            titleSuggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
            titleSuggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
            titleSuggestIndex.setKeywordPinyin(new Completion(
                    new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
            titleSuggestIndex.setKeywordSequence(new Completion(
                    new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));
            // 更新关键字索引库
            esTemplate.save(titleSuggestIndex);
            // 业务执行完毕，手动返回ack
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                // redelivered == true代表该消息已经消费过，丢弃消息，如果为false，代表消息未消费过，重新归队再次消费
                if (msg.getMessageProperties().isRedelivered()) {
                    channel.basicReject(msg.getMessageProperties().getDeliveryTag(), false);
                } else {
                    channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }


    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.ALBUM_DOWN_QUEUE),
            exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = {RabbitConstant.ALBUM_DOWN_RK}
    ))
    public void downAlbum(String message) {
        long albumId = Long.parseLong(message);
        log.info("接收到专辑服务投递的消息，删除了id为：【{}】的专辑", albumId);
        esTemplate.delete(String.valueOf(albumId), AlbumInfoIndex.class);
        esTemplate.delete(String.valueOf(albumId), SuggestIndex.class);
    }

}
